<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/view/include/css-include.jsp"%>
<%@ include file="/view/include/jsp-include.jsp"%>
<%@ include file="/view/include/jquery-include.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TMI</title>

<script type="text/javascript">
<%--============================= 전역변수 선언 ==========================--%>

//행추가
<%-- <tr id="dynamicDetailAddRow"> 에서 dynamicDetail 까지 중요함..조회, 초기화 시킬때 dynamicDetail으로 시작하는 ID 값 삭제 해줌 
(행추가와, 조회 후 한방에 처리할려면 ID값 다쓰면 귀찮아짐)

ex:
- 행추가는 dynamicDetailAddRow
- 조회 후 생성되는 ROW는dynamicDetailSearchRow 
등으로   dynamicDetail로 조회, 초기화시 한방에 지울 수 있게하자..
--%>
/* ordDetailTable에 view화면 호출, 행추가, 초기화 시 필요     */
 var dynamicAddRow = "<tr id='dynamicDetailAddRow'>"
                    +"<td width='5%' >New</td>"
                    +"<td width='10%' ><input type='text' class='inSTR100' name='goodsCode' readonly onFocus='blur();' /></td>"
                    +"<td width='40%'><input type='text' class='inSTR90'  style='margin-top:3px;' name='goodsName' readonly onFocus='blur();' /><img src='/images/web/bkn_zoom.gif' align='center' onclick='onProductPopup(this);'> </td>"
                    +"<td width='10%'> <input type='text' class='inST100'  name='qty' onkeydown='onlyNum(event);' maxlength='7'/></td>"
                    +"<td width='15%'> <input type='text' class='inSTR100' name='unit' readonly onFocus='blur();'/></td>"
                    +"<td width='10%'> <input type='text' class='inST100'  name='remark' maxlength='10'/></td>"
                    +"<td width='10%'> <img src='images/web/ic_x.gif' align='right' alt='Delete' onclick='deleteTmpRow(this);'> </td>"    //행 추가후  삭제 버튼 추가
                    +"</tr>";
 var popType ="";
    <%--============================= window onload ==========================--%>

    $().ready(function() {

        <%-- 달력 --%>
        calendar.makeCalender("ordDate");
        calendar.makeCalender("reqDate");
        calendar.makeCalender("schDate");
        
        <%-- ordDetailTable에입력항목 생성 --%>
        $("table[id='ordDetailTable']").append(dynamicAddRow);  // 전역변수로 잡아둔 값 셋팅
        
        <%-- 버튼설정 --%>
        /* 초기화버튼 */
        $("#reSetBtn").bind("click",function(){
        	  reSetFrm();
        });
        

        /* 오더 컨펌 버튼*/
        $("#confBtn").bind("click",function(){
             orderDivisionView();
        });
        
        /* DETAIL ROW 행추가 버튼 설정 */
        $("#detailAddRow").bind("click",function(){
            $("table[id='ordDetailTable']").prepend(dynamicAddRow);  // 전역변수로 잡아둔 값 셋팅
        });
        
        /* 오더번호 생성 */
/*         $("#ordNo1").bind("focusout",function(){  //ordNo2 조회
            if( $("#saveStatus").val() =="SAVE" && $("#ordNo1").val() != ""){   //신규 일때만 조회
                $.post('/getMaxOdrSeq.json', {
                         ordNo1 : $("#ordNo1").val()
                      },
                function(data) { 
                      if(data.ordNo2  == null || data.ordNo2 ==""){
                          alert("Error!!");
                      }else{
                            $("#ordNo2").val( data.ordNo2 ); //조회한 오더 SEQ 값 입력
                      }
                });
            }
        });
  */       
        /* 오더 조회 팝업 버튼 */
        $("#searchBtn").bind("click",function(){
            orderNumPopCall();
        });
        
        /* 저장버튼 */
        $("#saveBtn").bind("click",function(){       
            $("form[name='orderFrm']").submit();
        });

        /* 오더 삭제 */
        $("#deleteBtn").bind("click",function(){
            orderDelete();
        });
        
        /* 메인폼 서브밋 */
        $("form[name='orderFrm']").ajaxForm({
            dataType: "json",
            beforeSerialize: function($form, options) {
                //return $("form[name='orderFrm']").valid();  jquery 벨류데이션 플러그인 사용시
                 if( !validation() ){       //화면 항목 점검 시작
                    return false;
                }
                 if(!confirm("Save?")){
                    return false;
                 }
            },
            success:function(data) {
               if(data.result == true){
            	   if(data.resultDup == 'N'){
                       alert("Order No : duplication");
                       $("#ordNo1").focus();
                   }else{
	                   alert("Complete the save");
                       if($("#saveStatus").val() == "SAVE"){
                           alert("Please, Check Your Order Confirm!!");
                      }
	                   searchDataMaping(data);   //조회 데이터 맵핑 펑션
                   }
               }               
           },
           error:function(){alert("error!!");}
        }); 
        
    });
    
    <%--============================= function ==========================--%>
    /* 초기화 펑션 */
    function reSetFrm(){
	    	$("form[name='orderFrm']").each(function(){
	            this.reset();
	      });
	      
	      //reSetValidete(); //벨류데이션 체크 초기화;
	      $("#cnt").html("(0 / ");  // textarea 초기화
	      $("#ordNo1").attr({        // ordNo1 입력가능하게
	          onFocus : "",
	          readonly: false
	      });
	      $("#saveStatus").val("SAVE");     //신규 입력 상태로 변경
	      $("table[id='ordDetailTable']").empty().append(dynamicAddRow); // 지운 후 다시 입력항목 셋팅.. (css상 span id로하면 디자인깨짐, .html 로 하면 그리드 제목 까지 해줘야해서 귀찮음.. , 조회후에는 지워만주자)
	      $("span[id='delBtn']").show();
	      $("span[id='addRow']").show();
    }
    /* 조회 펑션 */
    function view(ordNo1 , ordNo2){
        $.post(
                '/getOrderView.json', {
                ordNo1 : ordNo1,
                ordNo2 : ordNo2
                },
            function(data) {
                searchDataMaping(data);    //DATA맵핑 
            });
    }
    
    /* 삭제 펑션 */
    function orderDelete(){
        if( $("#ordNo1").val() == "" || $("#ordNo2").val() == "" ){
            alert("search plz.");
            return;
        }
        
    	if(confirm("ORDER DELETE?")){
	        $.post(
	                '/deleteOrder.json', {
	                ordNo1 : $("#ordNo1").val(),
	                ordNo2 : $("#ordNo2").val()
	                },
	            function(data) {
	                	if(data.result == true){
		                	alert("OK!!");
		                	reSetFrm();    //DATA맵핑 
		                	$("span[id='delBtn']").show();
	                	}else{
	                		alert("ERROR");
	                	}
	            });
    	}
    }
    
    /* odrDetail 삭제 펑션 */
    function delOdrDetail(idx , rowNum){
        if(confirm("Delete?")){
            $.post(                                    //삭제Mothod 호출
                   '/delOdrDetail.json', {
                    ordSeq : idx    // 파라미터명 : 값
                    },
              function(data) {
                    if(data.result == true){
                        alert("OK!");
                        $("#dynamicDetailSearchRow"+rowNum).remove();    // 삭제한ROW 삭제함..
                    }else{
                        alert("error: error!!");
                    }
           });  
        }
    }
    
    /* searchData 맵핑 */
    function searchDataMaping(data){
        var val = ""; 
	        for(var v in data.resultMap) {       //상단 조회 결과 맵핑 조회return값이 한건임
	            $("#"+v).val(data.resultMap[v]);
	
	            if(v == "delCnt"){
	            	if(data.resultMap[v] > 0){
	            		$("span[id='delBtn']").hide();
	            		$("span[id='addRow']").hide();
	            	}else{
	            		$("span[id='delBtn']").show();
	            		$("span[id='addRow']").show();
	            	}
	            }
	            
	            if(v == "ordNo2"){
	            	$("#ordNo2").val(lpad( data.resultMap[v] , 3,"0"));
	            }
	            
	            if(v == "remark"){
	            	textAreaKyUp(data.resultMap[v]);
	            }
	            
	        }
	        $("#ordNo1").attr({           //조회후 ID값 (ordNo1) 수정못하게 막음
	            onFocus:"this.blur();", 
	            readonly:true
	        });
	
	        
	        //하단 그리드 맵핑
	        var contents = "";
	        $.each(data.resultDetailList, function(index){  // List로 받아온값 (여러건)
	            
	            //(Detail 테이블에 조회결과 입히기 jquery말고 그냥 onclick 걸어줌.. (조회 후 del 번튼에 key값 param변수로 입력)
	            var rowNum = index+1;
	
	            contents += "<tr id='dynamicDetailSearchRow"+rowNum+"'>"   
	                +'<td align="center" width="5%">'+rowNum+'</td>'
	                +'<td align="center"  width="10%">'+this.goodsCode+'</td>'
	                +'<td align="left"   width="40%">'+this.goodsName+'</td>'
	                +'<td align="right"  width="10%">'+this.qty+'</td>'
	                +'<td align="left"   width="15%">'+this.unit+'</td>'
	                +'<td align="center" width="10%">'+this.remark+'</td>'
	                +'<td align="center  width="10%"">';
	
	                if(this.ordStatus == "N"){
	                	
	                contents += '<img src="images/web/ic_up.gif" alt="Update" align="left" id="onUpdate" onclick="viewDialogOpen('+this.ordSeq+' , \''+this.qty+'\',\''+this.remark+'\')" />'   //onclick= 업데이트다이얼 로그 ( 키값)
	                         +'<img src="images/web/ic_x.gif" alt="Delete" align="right" id="onDelete" onclick="delOdrDetail('+this.ordSeq+','+rowNum+')"/>'   //onclick= 삭제 펑션 호출 ( 키값, 해당ROW값)
	                         
	                }
	                +"</td></tr>";     
	        });
	        $("table[id='ordDetailTable']").empty().append(contents);  // 조회 값 뿌리기
	 
	        $("#saveStatus").val("UPDATE"); // 상태값 UPDATE로 변경
    }
    
    <%--================================= FORM 컨트롤 ============================--%>
    /* 사용자가 추가한 행 삭제 */
    function deleteTmpRow(obj){
        $(obj).parent().parent().remove();     // 사용자가 동적 생성한 ODR DETAIL ROW삭제
    }

    function validation(){

        var ordNo1          = $("#ordNo1").val();
        var ordDate         = $("#ordDate").val();
        var reqDate         = $("#reqDate").val();
        var schDate         = $("#schDate").val();
        
        if(ordNo1==null           || ordNo1=="") {   alert("order No: Required fields."); $("#ordNo1").focus(); return false; }
        if(ordNo1.length < 5) {   alert("order No: Enter the 5 characters"); $("#ordNo1").focus(); return false; }
        
        if( !isValidDate(ordDate,"Order Date") ){ $("#ordDate").focus(); return false; }
        if( !isValidDate(reqDate,"Requset Date") ){ $("#reqDate").focus(); return false; }
        if( !isValidDate(schDate,"Schedule Date") ){ $("#schDate").focus(); return false; }
/*      var ordDate         = $("#ordDate").val();
        var originCode      = $("#originCode").val();
        var originName      = $("#originName").val();
        var packingDesc     = $("#packingDesc").val();
        var reqDate         = $("#reqDate").val();
        var priceBase       = $("#priceBase").val();
        var scheduleDate    = $("#scheduleDate").val();
        var portOfLoadName  = $("#portOfLoadName").val();
        var transMethodName = $("#transMethodName").val();
 */
        
        
/*      if(ordDate==null         || ordDate=="") { alert("ordDate 입려하시오."); $("#ordDate").focus(); return false; }
        if(originCode==null      || originCode=="") { alert("originCode 입려하시오."); $("#originCode").focus(); return false; }
        if(originName==null      || originName=="") { alert("originName 입려하시오."); $("#originName").focus(); return false; }
        if(packingDesc==null     || packingDesc=="") { alert("packingDesc 입려하시오."); $("#packingDesc").focus(); return false; }
        if(reqDate==null         || reqDate=="") { alert("reqDate 입려하시오."); $("#reqDate").focus(); return false; }
        if(priceBase==null       || priceBase=="") { alert("priceBase 입려하시오."); $("#priceBase").focus(); return false; }
        if(scheduleDate==null    || scheduleDate=="") { alert("scheduleDate 입려하시오."); $("#scheduleDate").focus(); return false; }
        if(portOfLoadName==null  || portOfLoadName=="") { alert("portOfLoadName 입려하시오."); $("#portOfLoadName").focus(); return false; }
        if(transMethodName==null || transMethodName=="") { alert("transMethodName 입려하시오."); $("#transMethodName").focus(); return false; }

        if( !isValidDate(ordDate,"ordDate") ){ $("#ordDate").focus(); return false; }
        if( !isValidDate(reqDate,"reqDate") ){ $("#reqDate").focus(); return false; }
        if( !isValidDate(scheduleDate,"scheduleDate") ){ $("#scheduleDate").focus(); return false; }
        
 */     

        for(var i=0 ; i < $("[name=goodsCode]").length ; i++){
        	var goodsCodeTmp = $("[name=goodsCode]").eq(i).val();
        	var qtyTmp = $("[name=qty]").eq(i).val();
        	
        	if(goodsCodeTmp==null   || goodsCodeTmp=="") { alert("goodsCode: Required fields."); $("[name=goodsCode]").eq(i).focus(); return false; }
        	if(qtyTmp==null         || qtyTmp=="") { alert("Quantity: Required fields."); $("[name=qty]").eq(i).focus(); return false; }
            if(qtyTmp < 1) { alert("qty > 0 !!"); $("#qty").eq(i).focus(); return false; }
        }
      
      return true;      
    } 

    /* textarea 체크 */
    var oldStr;
    function textAreaKyUp(val){

        var str = val;
        if(str.length <= 200){
            oldStr = str;
            contents = "("+str.length+" / ";
            $("#cnt").html(contents);
        }else{
            alert("over length!!");
            $("#remark").val(oldStr);
        }
    };
    
    

    /*     
        // 기본폼 체크   jquery 벨류데이션 플러그인 사용시
        $().ready(function() {
            $("form[name='orderFrm']").validate({
                errorClass:"errorLeft",
                rules:{
                    ordNo1:{ required: true },
                    ordDate:{ required: true , dateISO: true},
                    originCode:{ required: true , number: true },
                    originName: {required: true},
                    packingDesc: {required: true},
                    reqDate:{ required: true , dateISO: true},
                    priceBase:{ required: true },
                    scheduleDate:{ required: true , dateISO: true},
                    portOfLoadName:{ required: true },
                    transMethodName:{ required: true }
                },
                messages:{
                    ordNo1:{ required: "필수 항목 입니다."},
                    ordDate:{ required: "필수 항목 입니다." , dateISO:"YYYY-MM-DD"},
                }
            });
        });
        
        // 벨류데이션 초기화
         function reSetValidete(){
            $("form[name='orderFrm']").validate().resetForm(); //벨류데이션 체크 초기화;
        }
       */  
       
    /************************************************************************/
    /*                          view POPUP , 리턴값처리                     */
    /************************************************************************/
    function viewDialogOpen(ordSeq , qty , remark){
        $("#pop_ordSeq").val(ordSeq);
        $("#pop_qty").val(qty);
        $("#pop_remark").val(remark);
        
        $("#viewDialog").dialog({
            modal:true, 
            width:300,
            title:"Detail Update"
        });
    }


    /* detail update*/
    function detailUpdate(){
/*         if(confirm("Update?")){ */
            $.post("/detailUpdate.json",{
                ordSeq      : $("#pop_ordSeq").val(),
                qty         : $("#pop_qty").val(),
                remark      : $("#pop_remark").val()
            },function(data){
                if(data.result == true){
                    $("#viewDialog").dialog("close");
                    view($("#ordNo1").val() , $("#ordNo2").val());
                }
            });
/*         } */
    }

    /* 오더 검색 팝업 버튼 */
    function orderNumPopCall(){
        window.open('/orderNumPop.html', 'orderNumPop', 'width=415, height=500, toolbar=no, location=no, status=no, menubar=no, scrollbars=no');
    };
        
    /* 고객 팝업 버튼 */
    function customerPopCall(type , customer){
        popType = type;     
        window.open('/customerPop.html?customer='+customer, 'customerPop', 'width=415, height=500, toolbar=no, location=no, status=no, menubar=no, scrollbars=no');
    };

    /* 상품 팝업 버튼 */
    var objIndex = 0;
    function onProductPopup(obj){
    	objIndex = $("table[id='ordDetailTable'] img").index(obj);
        window.open('/productPop.html', 'changeProductPop', 'width=615, height=450, toolbar=no, location=no, status=no, menubar=no, scrollbars=no');
    }

    function productPopValue(goodsCode, goodsName, unit, boxQty, hsCode, productCode, custCode, custName){

    	$("[name=goodsCode]").eq(objIndex).val(goodsCode);
    	$("[name=goodsName]").eq(objIndex).val(goodsName);   
    	$("[name=unit]").eq(objIndex).val(unit);      
    }
    
    /* 고객정보 맵핑 */
    function customerPopValue(custCode , custName , addr1 , addr2, tel, fax){

        switch(popType){
        case "S": 
                $("#sCustCode").val(custCode);
                $("#sCustName").val(custName);
                $("#sAddr1").val(addr1);
                $("#sAddr2").val(addr2);
                $("#sTel").val(tel);
                $("#sFax").val(fax);
            break;
        case "M":
                $("#mCustCode").val(custCode);
                $("#mCustName").val(custName);
                $("#mAddr1").val(addr1);
                $("#mAddr2").val(addr2);
                $("#mTel").val(tel);
                $("#mFax").val(fax);
                
                if( $("#nCustCode").val() == "" ){
                    
                    $("#nCustCode").val(custCode);
                    $("#nCustName").val(custName);
                    $("#nAddr1").val(addr1);
                    $("#nAddr2").val(addr2);
                    $("#nTel").val(tel);
                    $("#nFax").val(fax);
                }
            break;
        case "N":
                $("#nCustCode").val(custCode);
                $("#nCustName").val(custName);
                $("#nAddr1").val(addr1);
                $("#nAddr2").val(addr2);
                $("#nTel").val(tel);
                $("#nFax").val(fax);
            break;
      }
        popType = "";
    };
    
    
    
    
    

    /*********************************오더 분할*****************************************/
        /* 오더분할 */
    function orderDivisionView(){
        if( $("#ordNo1").val() == "" || $("#ordNo2").val() == ""){
            alert("search plz.");
            return;
        }
        
        $("#confOrdNum").val( $("#ordNo1").val() );
        $("#confOrdNo1").val( $("#ordNo1").val() );
        $("#confOrdNo2").val( $("#ordNo2").val() );
        $("#confOrdPseq").val("");
        $("#realConfOrdPSeq").val("");
        $("#btnType").val("");
        

        $("#orderDivisionView").dialog({
            modal:true, 
            width:600,
            title:"Order Conf"
        });
        
        getOrderDivisionList("DEFAULT");
        
    }
    
    /* 오더분할 조회*/
    function getOrderDivisionList(type){
    	if(type == "NEW"){
            var realConfOrdPseq = $("#realConfOrdPseq").val();
            var confOrdPseq     = $("#confOrdPseq").val();
            
            if( realConfOrdPseq < confOrdPseq || realConfOrdPseq == 0){
                alert("Now New Data!!");
                return;
            }
            
    	}
    	
            $("table[id='divisionDetailTable']").empty(); //분할 데이터 테이블 삭제

            $.post("/getOrderDivisionList.json",{
                confOrdNo1      : $("#confOrdNo1").val(),
                confOrdNo2      : $("#confOrdNo2").val(),
                type            : type
            },function(data){
                searchDataMapingDivision(data);
            });
        }
    
    /* 오더 분할 searchData 맵핑 */
    function searchDataMapingDivision(data){
        //상단 정보 셋팅
        var searchOrdPseq = data.resultConfSearchOrdPseq;
        var confOrdPseqMax = data.resultConfMaxOrdPseq;
        var type  = data.type;

        if(confOrdPseqMax == 0){
            //초기값 1로 입력
            $("#confOrdPseq").val("1");
            $("#realConfOrdPseq").val(confOrdPseqMax);
        }else if(confOrdPseqMax > 0 ){
        	if (type == "SAVE"){
        		$("#confOrdPseq").val( parseInt(confOrdPseqMax)+1 );
        	}else if(type == "TOPSEARCH"){
        		$("#confOrdPseq").val(searchOrdPseq);
        	}else{
        		$("#confOrdPseq").val(confOrdPseqMax);	
        	}
            $("#realConfOrdPseq").val(confOrdPseqMax);
        }else{
            $("#confOrdPseq").val( parseInt( $("#realConfOrdPseq").val() ) +1 );
        }
        

        var contents = "";
        $.each(data.resultDivisionList, function(index){  // List로 받아온값 (여러건)
            
            //(Detail 테이블에 조회결과 입히기 jquery말고 그냥 onclick 걸어줌.. (조회 후 del 번튼에 key값 param변수로 입력)
            var rowNum = index+1;
            
            contents += "<tr id='"+rowNum+"'>"
                +'<td align="center" width="10%">'+rowNum+'</td>'
                +'<td align="center"  width="10%"><input type="hidden" name="confGoodsCode" value="'+this.confGoodsCode+'" />'
                +this.confGoodsCode+'</td>'
                +'<td align="left"   width="50%">'+this.confGoodsName+'</td>'
                +'<td align="right"  width="15%">'
                +'<input type="text" class="inST100" name="confQty" id="confQty" onkeydown="onlyNum(event);" value="'+this.confQty+'" maxlength="7"/>'
                +'<input type="hidden" class="inST100" name="realConfQty" id="realConfQty" value="'+this.confQty+'" />'
                +'<input type="hidden" class="inST100" name="reMainConfQty" id="reMainConfQty" value="'+this.reMainConfQty+'" />'
                +'<input type="hidden" class="inST100" name="confOrdSeq" id="confOrdSeq" value="'+this.confOrdSeq+'" />'
                +'</td>'
                +'<td align="left"   width="15%">'+this.confUnit+'</td>'
                +"</tr>";     
            
        });
        $("table[id='divisionDetailTable']").empty().append(contents);  // 조회 값 뿌리기
 
    }
    
    
    
    /* 등록 , 수정, 삭제 */
    function actionOrderDivision(btnType){

    	var realConfOrdPseq = $("#realConfOrdPseq").val();
        var confOrdPseq     = $("#confOrdPseq").val();
        var msg = "";
        if(btnType == "SAVE"){
            if( confOrdPseq <= realConfOrdPseq  ){
                $("#btnType").val("UPDATE");
                msg = "UPDATE";
            }else if( confOrdPseq > realConfOrdPseq){
                $("#btnType").val("INSERT");
                msg = "SAVE";
            }
        }else if(btnType == "DELETE"){
        	$("#btnType").val("DELETE");
        	msg = "DELETE";
        }
        
        /* 폼 서브밋 */
        $("form[name='orderDivisionFrm']").ajaxForm({
            dataType: "json",
            beforeSerialize: function($form, options) {
                
                 if(!confirm(msg+"?")){
                    return false;
                 }

                 if( (( parseInt(realConfOrdPseq) - parseInt(confOrdPseq) ) < 0 ) && msg == "DELETE"   ){
                     alert("New Data!!");
                     return false;
                }
                 
                 if( (( parseInt(realConfOrdPseq) != parseInt(confOrdPseq) ) ) && msg == "DELETE"   ){
                       alert("Intermediate data can not be deleted!!");
                       return false;
                 }

                 if (msg !="DELETE"){
	                 if( !divisionValidation() ){       //화면 항목 점검 시작
	                     return false;
	                 }
                 }

            },
            success:function(data) {
               if(data.result == true){
                   alert("Complete the save");
                   searchDataMapingDivision(data);   //조회 데이터 맵핑 펑션
               }else{
            	   alert("PACKING DATA!! no delete");
               }
           },
           error:function(){alert("error!!");}
        });
        
        $("form[name='orderDivisionFrm']").submit();
    }
    
    
    

    /* 오더분할 위에 버튼 조회*/
    function searchOrderDivisionList(type){
	        var realConfOrdPseq = $("#realConfOrdPseq").val();
	        var confOrdPseq     = $("#confOrdPseq").val();
	        var confMaxOrdPseq  = "";
	        
	        if(type == "left" ){
	        	if(parseInt(confOrdPseq) ==1){
	        		alert("First Data!!");
	        		return;
	        	}else{
	        		confMaxOrdPseq = parseInt(confOrdPseq)-1;
	        	}
	        }
	        if(type == "right" ){
	        	if(parseInt(realConfOrdPseq) <= parseInt(confOrdPseq)){
                    alert("Last Data!!");
                    return;
                }else{
                	confMaxOrdPseq = parseInt(confOrdPseq)+1;
                }
            }
	        
            $.post("/searchOrderDivisionList.json",{
                confOrdNo1      : $("#confOrdNo1").val(),
                confOrdNo2      : $("#confOrdNo2").val(),
                confMaxOrdPseq  : confMaxOrdPseq,
                realConfOrdPseq : realConfOrdPseq
            },function(data){
            	searchDataMapingDivision(data);
            });
        }
    
    
    
    
    /* 분할 팝업 닫기 */
    function orderDivisionClose(){
    	$("#orderDivisionView").dialog("close");
    	view($("#ordNo1").val() , $("#ordNo2").val());
    }
    
    function detailClose(){
        $("#viewDialog").dialog("close");
        view($("#ordNo1").val() , $("#ordNo2").val());
    }
    
    
    /*정합성 체크*/
    function divisionValidation(){
        if($("[name=confOrdSeq]").length <= 0){
        	//alert("등록할 데이터가 없습니다.");
        	alert("No data register.");
        	return;
        }
    	for(var i=0 ; i < $("[name=confOrdSeq]").length ; i++){
    		
    		var confQtyTmp = $("[name=confQty]").eq(i).val();
    		var realConfQtyTmp = $("[name=realConfQty]").eq(i).val();
    		var reMainConfQtyTmp = $("[name=reMainConfQty]").eq(i).val();
    		
    		if( confQtyTmp == null || confQtyTmp ==""){
    			//alert("오더 분할 값을 입력 하세요.");
    			alert("Order Division Enter the value.");
    			$("[name=confQty]").eq(i).focus();
    			return false;
    		}
    		
    		if( parseInt(confQtyTmp) < 0 ){
                //alert("0보다 작은값일 수 없습니다.\n원수량:"+reMainConfQtyTmp);
                alert("Qty > 0 \n Original quantity:"+reMainConfQtyTmp);
	   			$("[name=confQty]").eq(i).focus();
	   			return false;
	    	}
    		
    		if( $("#btnType").val() == "INSERT" ){
	    		if( parseInt(confQtyTmp) > parseInt(realConfQtyTmp) ){
	   			    //alert("실제 수량 보다 수량이 초과하였습니다.\n남은수량:"+realConfQtyTmp+", 입력수량:"+confQtyTmp);
	   			    alert("Over Qty! \n남은수량:"+realConfQtyTmp+", 입력수량:"+confQtyTmp);
	   				$("[name=confQty]").eq(i).focus();
	   				return false;
	    	     }
    		}else{
    			if( parseInt(confQtyTmp) > ( parseInt(reMainConfQtyTmp)+parseInt(realConfQtyTmp) ) ){
                    alert("실제 수량 보다 수량이 초과하였습니다.\n남은수량:"+reMainConfQtyTmp+", 원수량:"+reMainConfQtyTmp+", 입력수량:"+confQtyTmp);
                    $("[name=confQty]").eq(i).focus();
                    return false;
                 }
    		}
    	}
    	
      return true;      
    } 
</script>
</head>


<body>
<div class="wrap">
    <div class="pagetitle">
        <h1>ORDER</h1>
    </div>
    <div class="">
    <!-- 레이어 팝업시작 -->
        <div id="viewDialog" style="display: none; background: white;">
         <input type="hidden" id="pop_ordSeq">
           <table class="TableST">
             <tr>
               <th>Quantity</th>
               <td><input type="text" name="pop_qty" id="pop_qty" class="inST50" onkeydown="onlyNum(event);" maxlength="7"/></td>
              </tr>
             <tr>
               <th>Remarks</th>
               <td><input type="text" name="pop_remark" id="pop_remark" class="inST50" maxlength="10"/></td>
              </tr>
           </table>
            <div class="bo_btn">
                <ul class="btnst"><li class="a"><a href="javascript: detailUpdate();" id="save" >Save</a></li></ul>
                <ul class="btnst"><li class="a"><a href='javascript:detailClose();' >CLOSE</a></li></ul>
            </div>    
       </div>


        <!-- 오더 분할 -->
       <div id="orderDivisionView" style="display: none; background: white;">
       <form name="orderDivisionFrm" method="post" action="/actionOrderDivision.json"> <%--리턴값 json으로 설정 --%>
                <input type="text" class="inSTR20" id="confOrdNum" name="confOrdNum" readonly onFocus="blur();" value=""/>
                <a href="javascript:searchOrderDivisionList('left');" id="" >◀</a>
                <input type="text" class="inSTR5" id="confOrdPseq" name="confOrdPseq" readonly onFocus="blur();" value=""/>
                <a href="javascript:searchOrderDivisionList('right');" id="" >▶</a>
                <input type="hidden" id="confOrdNo1" name ="confOrdNo1" />
                <input type="hidden" id="confOrdNo2" name ="confOrdNo2" />
                <input type="hidden" id="realConfOrdPseq" name ="realConfOrdPseq" />
                <input type="hidden" id="btnType" name ="btnType" />
                <br>
            <div class="taHeadW">
                <table class="TableST2Head" >
                    <tr>
                        <th width="10%">No</th>
                        <th width="10%">Code</th>
                        <th width="50%">Description</th>
                        <th width="15%">Quantity</th>
                        <th width="15%">Unit</th>
                    </tr>
                </table>
            </div>
            <div class="taBodyW">
                <table class="TableST2Body" id="divisionDetailTable">
                </table>
            </div>
        <div class="bo_btn">
            <ul class="btnst"><li class="a"><a href='javascript:getOrderDivisionList("NEW");'  >NEW</a></li></ul>
            <ul class="btnst"><li class="a"><a href='javascript:actionOrderDivision("DELETE");'>DELETE</a></li></ul>
            <ul class="btnst"><li class="a"><a href='javascript:actionOrderDivision("SAVE");' >SAVE</a></li></ul>
            <ul class="btnst"><li class="a"><a href='javascript:orderDivisionClose();' >CLOSE</a></li></ul>
        </div>
        </form>
       </div>
    <!-- 레이어 팝업끝 -->   
          
       
    <form name="orderFrm" method="post" action="/saveOrder.json"> <%--리턴값 json으로 설정 --%>
    <input type="hidden" id ="saveStatus" name="saveStatus" value="SAVE" />     <%-- 조회, 수정, 초기화, 최초 입력 시 필요 (최초, 초기화 후 = SAVE   ,  수정, 조회 후 = UPDATE)--%>
    
        <table class="TableST">
            <tr>
                <th>Order No</th>
                <td colspan="3">
                    <input type="text" class="inST20" id="ordNo1" name="ordNo1" maxlength="20" value=""/>
                    <img alt="Search" height="16" onclick="orderNumPopCall();" src='/images/web/bkn_zoom.gif' align='absmiddle'>
                    <input type="hidden" class="inSTR10" id="ordNo2" name="ordNo2" readonly onFocus="blur();" value="001"/></td>
            </tr>
            <tr>
                <th>Order Date</th>
                <td colspan="3">
                    <input type="text" class="inST20" id="ordDate" name="ordDate" maxlength="10"/>
            </tr>
            <tr>
                <th >Shipper</th>
                <td colspan="2">
                    <input type="text" class="inSTR10" id="sCustCode" name="sCustCode" readonly onFocus="blur();" value=""/><img alt="Search" height="16" onclick="customerPopCall('S',1)" src='/images/web/bkn_zoom.gif' align='absmiddle'>
                    <input type="text" class="inSTR80" id="sCustName" style="width:81%;" name="sCustName" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90" id="sAddr1" name="sAddr1" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th> </th>
                <td><input type="text" class="inSTR100"id="sTel" name="sTel" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90" id="sFax" name="sFax" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90" id="sAddr2" name="sAddr2" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th >Messrs</th>
                <td colspan="2">
                    <input type="text" class="inSTR10" id="mCustCode" name="mCustCode" readonly onFocus="blur();" value=""/><img alt="Search" height="16" onclick="customerPopCall('M',2)" src='/images/web/bkn_zoom.gif' align='absmiddle'>
                    <input type="text" class="inSTR80" id="mCustName" style="width:81%;" name="mCustName" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90" id="mAddr1" name="mAddr1" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th></th>
                <td><input type="text" class="inSTR100" id="mTel" name="mTel" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90"  id="mFax" name="mFax" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90"  id="mAddr2" name="mAddr2" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th >Notify Party</th>
                <td colspan="2">
                    <input type="text" class="inSTR10" id="nCustCode" name="nCustCode" readonly onFocus="blur();" value=""/><img alt="Search" height="16" onclick="customerPopCall('N',2)" src='/images/web/bkn_zoom.gif' align='absmiddle'>
                    <input type="text" class="inSTR80" id="nCustName" style="width:81%;" name="nCustName" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90" id="nAddr1" name="nAddr1" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr>
                <th></th>
                <td><input type="text" class="inSTR100" id="nTel" name="nTel" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90"  id="nFax" name="nFax" readonly onFocus="blur();" value=""/></td>
                <td><input type="text" class="inSTR90"  id="nAddr2" name="nAddr2" readonly onFocus="blur();" value=""/></td>
            </tr>
            <tr> 
                <th>Origin</th>
                <td colspan="3">
                    <input type="text" class="inST97" id="origin" name="origin" style="width:96%;" maxlength="50" value=""/>
                </td>
            </tr>
            <tr>
                <th>Packing</th>
                <td colspan="3">
                    <input type="text" class="inST97" id="packing" name="packing" style="width:96%;" maxlength="100" value=""/>
                </td>
            </tr>
            <tr>
                <th>Requset Date</th>
                <td>
                    <input type="text" class="inST80" id="reqDate" name="reqDate" maxlength="10" value=""/>
                </td>
                <th class="thST2">Price base</th>
                <td>
                    <input type="text" class="inST90" id="priceBase" name="priceBase" maxlength="30" value=""/>
                </td>
            </tr>
            <tr>
                <th>Schedule Date</th>
                <td>
                    <input type="text" class="inST80" id="schDate" name="schDate" maxlength="10"/>
                </td>
                <th class="thST2">Port of Loading</th>
                <td>
                    <input type="text" class="inST90" id="portLoad" name="portLoad" maxlength="30" value=""/>
                </td>
            </tr>
            <tr>
                <th>Dispatch</th>
                <td><input type="text" class="inST90" id="dispatch" name="dispatch" maxlength="30" value=""></td>
                <th class="thST2">Destination</th>
                <td>
                    <input type="text" class="inST90" id="destination" name="destination" maxlength="30" value=""/>
                </td>
            </tr>
        </table>
        <br>
        <div class="bo_btn">
            <span id="addRow"><ul class="btnst"><li class="a"><a href="#" id="detailAddRow" >ADD</a></li></ul></span>
        </div> 
    
        <div class="taHeadW">
            <table class="TableST2Head" >
                <tr>
                    <th width="5%">No</th>
                    <th width="10%">Code</th>
                    <th width="40%">Description</th>
                    <th width="10%">Quantity</th>
                    <th width="15%">Unit</th>
                    <th width="10%">Remarks</th>
                    <th width="10%">U&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;D</th>
                </tr>
            </table>
        </div>
        <div class="taBodyW">
            <table class="TableST2Body" id="ordDetailTable">
            </table>
        </div>    
        <br />
        <table class="TableST3">
            <tr>
                <th width="20%">Remarks<br><span id="cnt">(0 / </span>200)</th>
                <td><textarea class="teST80" wrap="virtual" id="remark" onkeyup="textAreaKyUp(this.value);" name="ordRemark"></textarea></td>
            </tr>
        </table>
    </div>
    
    <div class="bo_btnLeft">
    <ul class="btnst"><li class="a"><a href="#" id="confBtn" >ORDER CONF</a></li></ul>
    </div>
    <div class="bo_btn">
        
        <ul class="btnst"><li class="a"><a href="#" id="reSetBtn" >INIT</a></li></ul>
        <ul class="btnst"><li class="a"><a href="#" id="searchBtn" >SEARCH</a></li></ul>
        <ul class="btnst"><li class="a"><a href="#" id="saveBtn" >SAVE</a></li></ul>
        <span id="delBtn"><ul class="btnst"><li class="a"><a href="#" id="deleteBtn" >DELETE</a></li></ul></span>
    </div>
 </form>
</div>
</body>
</html>